<template>
  <el-dialog
    :model-value="dialogVisible"
    width="30%"
    @close="handleClose"
    :show-close="false"
    destroy-on-close
  >
    <template #header>
      <div class="title-container">
        <span class="title">{{ dialogTitle }}</span>
        <el-tooltip placement="bottom" effect="light">
          <template #content>
            <span style="font-size: 12px; font-weight: 600">命名举例:</span
            ><br />
            <div
              class="inner-desc"
              style="margin-top: 5px; border: 1px dashed #c0c4cc; padding: 5px"
            >
              个人中心:<br />path:/account<br />
              component:Layout<br />
              信息管理:<br />path:person/infoManager<br />
              component:account/person/infoManager
            </div>
          </template>
          <el-icon><QuestionFilled /></el-icon>
        </el-tooltip>
      </div>
    </template>
    <el-form
      ref="ruleForm"
      :model="form"
      label-width="88px"
      :rules="rules"
      status-icon
    >
      <el-form-item label="上级菜单" prop="pid">
        <el-select
          v-model="form.pid"
          clearable
          filterable
          default-first-option
          placeholder="请选择父级菜单"
          :disabled="dialogTitle !== '增加菜单'"
        >
          <el-option
            v-for="item in options"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="菜单名称" prop="name">
        <el-input v-model.trim="form.name" />
      </el-form-item>
      <el-form-item
        label="菜单类型"
        v-if="props.dialogTitle !== '增加菜单'"
        prop="type"
      >
        <el-radio-group v-model="form.type">
          <el-radio :label="'1'">菜单</el-radio>
          <el-radio :label="'2'">按钮</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="权限值" prop="permissionValue">
        <el-input v-model="form.permissionValue" />
      </el-form-item>
      <el-form-item label="路由地址" prop="path">
        <el-input v-model="form.path" />
      </el-form-item>
      <el-form-item label="组件路径" prop="component">
        <el-input v-model="form.component" />
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">Cancel</el-button>
        <el-button type="primary" @click="handleConfirm">Confirm</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { defineEmits, defineProps, ref, watch } from 'vue'
import cloneDeep from 'lodash/cloneDeep'
import { addMenuList, updateMenuList } from '@/api/authority.js'
import { ElMessage } from 'element-plus/lib/components'
import { useStore } from 'vuex'

const store = useStore()

const ruleForm = ref(null)

const initForm = () => {
  return {
    id: '',
    pid: '',
    pidName: '',
    name: '',
    type: '',
    permissionValue: '',
    path: '',
    component: ''
  }
}

const form = ref(initForm())

const options = ref([])

const props = defineProps({
  dialogVisible: {
    type: Boolean,
    default: false,
    require: true
  },
  dialogTitle: {
    type: String,
    default: '',
    require: true
  },
  /* 当前选中行的数据 */
  dialogValue: {
    type: Object,
    default: () => {},
    require: true
  }
})

watch(
  [() => props.dialogValue],
  () => {
    // 下拉列表
    options.value = store.getters.menuNameAndIdList
    // 切记如果使用一个一个赋值就不是响应式了，就会出现原来的数据还存在
    // Object.assign(form.value, props.dialogValue) // 这种方式破坏了响应式不行
    form.value = props.dialogValue
  },
  {
    deep: true,
    immediate: true
  }
)

const emits = defineEmits(['update:modelValue', 'update:menuAndSelectInit'])

const validatePass = (rules, value, callback) => {
  if (value === '') {
    return callback(new Error('请输入菜单名称'))
  }
  setTimeout(() => {
    if (props.dialogTitle === '编辑菜单或按钮') {
      callback()
    } else {
      const res = store.getters.menuNameAndIdList.map((item) => item.name)
      if (res.includes(value)) {
        callback(new Error('菜单名称已存在,请重新输入'))
      } else {
        callback()
      }
    }
  }, 1000)
}

const rules = ref({
  pid: [
    {
      required: true,
      message: 'Please select senior menu',
      trigger: 'blur'
    }
  ],
  name: [
    {
      validator: validatePass,
      trigger: 'blur'
    }
  ],
  type: [
    {
      required: true,
      message: 'Please select type',
      trigger: 'blur'
    }
  ],
  permissionValue: [
    {
      required: true,
      message: 'Please input permissionValue',
      trigger: 'blur'
    }
  ],
  path: [
    {
      required: false,
      message: 'Please input path',
      trigger: 'blur'
    }
  ],
  component: [
    {
      required: false,
      message: 'Please input component',
      trigger: 'blur'
    }
  ]
})

const handleClose = () => {
  Object.assign(form.value, initForm())
  emits('update:modelValue', false)
}

const handleConfirm = () => {
  ruleForm.value.validate(async (valid) => {
    if (valid) {
      const { id, pid, name, type, permissionValue, path, component } =
        form.value
      const addForm = { pid, name, type, permissionValue, path, component }
      const modifyForm = {
        id,
        pid,
        name,
        type,
        permissionValue,
        path,
        component
      }
      // console.log(submitForm)
      if (props.dialogTitle === '编辑菜单或按钮') {
        try {
          await updateMenuList(modifyForm)
          ElMessage({
            type: 'success',
            duration: 1500,
            message: '更新成功'
          })
        } catch (error) {
          ElMessage({
            type: 'error',
            duration: 1500,
            message: error
          })
        }
      } else {
        try {
          await addMenuList(addForm)
          ElMessage({
            type: 'success',
            duration: 1500,
            message: '添加成功'
          })
        } catch (error) {
          ElMessage({
            type: 'error',
            duration: 1500,
            message: error
          })
        }
      }
      emits('update:menuAndSelectInit')
      handleClose()
    } else {
      console.log('error submit!!')
      return false
    }
  })
}
</script>

<style lang="scss">
.title-container {
  .title {
    margin-right: 5px;
    font-size: 18px;
  }
}
.inner-desc:hover {
  cursor: pointer;
  border: 1px dashed #409eff !important;
}
</style>
